﻿/*
 * Create By：Steven Jiang 
 * Create Date：2010-3-12
 * 
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.BusinessRule;

public partial class masterdata_PersonEdit : PageBase
{
    private decimal? id = null;
    private Person _person;
    private PersonManager manager;
    private Boolean ReadOnly;
    protected void Page_Load(object sender, EventArgs e)
    {
        ReadOnly = Request.QueryString.ToString().ToUpper().IndexOf("READONLY") > -1;
        
         manager = new PersonManager();
         if (!string.IsNullOrEmpty(Request["id"]))
         {
            
             try
             {
                 id = decimal.Parse(Request["id"]);
             }
             catch{}

         }

         if (Request["flag"] != null && Request["flag"].ToString() == "1")
         {
             btnSave.Visible = false;

         }
        
         if (!IsPostBack)
         {
             DataBind();
             //如果txtJoinDate被置为无效状态，则验证控件也必须无效
             if (txtJoinDate.Disabled)
                 rv1.Enabled = false;
             //设置最大时间
             rv1.MaximumValue = DateTime.Now.ToString("yyyy-MM-dd");
             rv1.MinimumValue = "1990-01-01";
             
             BindDDL();
             if (!string.IsNullOrEmpty(Request["id"]) && id != null)
             {
                 _person = manager.Load(id.Value);
                 if (_person != null)
                 {
                     txtHidOrg.Value = _person.OrgID.ToString();
                     txtOrg.Text = new OrgainzationManager().Load(_person.OrgID).NAME;
                     BindManager();
                     //ctlTable.DataSource = _person;
                     //ctlTable.DataBind();
                     RequiredFieldValidator1.Enabled = false;
                     txtCode.Disabled = true;
                     txtCode.Value = _person.Code;
                     
                     txtIdentity.Text = _person.Identity;
                     txtName.Value = _person.Name;
                     ddlPosition.SelectedValue = _person.Position;
                     this.ddlPosition.SelectedValue = _person.Position;
                   
                     txtTelephone.Value = _person.Telephone;

                     txtFax.Value = _person.FAX;


                     chkValid.Checked = _person.ACTIVE;
                     txtMail.Value = _person.EMAIL;
                     ddlSex.Value = _person.Sex;
                     ddlManager.SelectedValue = _person.MANAGERID.ToString();
                    
                 }
             }
            
         }
         else
         {
             //显示可供选择的员工号列表
            // BindCode();
         }
         if (ReadOnly)
         {
             btnSave.Visible = false;
         }
    }


   

    private void BindManager()
    {
        if (txtHidOrg.Value.Trim() != "")
        {
            string selfid = "-1";
            if(_person!=null)
                selfid = _person.ID.ToString();
            ddlManager.DataSource = new PersonManager().LoadByOrganizationID(int.Parse(txtHidOrg.Value.Replace("'","")),true,selfid,1);
            ddlManager.DataTextField = "NAME";
            ddlManager.DataValueField = "ID";
            ddlManager.DataBind();
            ddlManager.Items.Insert(0, new ListItem("--请选择--"));
        }
    }

    protected void BindDDL()
    {
        DictionaryItemsManager dim = new DictionaryItemsManager();
        this.ddlPosition.DataSource = dim.GetItemList(DictionaryEnum.UserPosition, MyStateManager.DomainID);
        this.ddlPosition.DataTextField = "NAME";
        this.ddlPosition.DataValueField = "DictionaryItemID";
        this.ddlPosition.DataBind();
        this.ddlPosition.Items.Insert(0, new ListItem("--请选择--"));
       
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
       
         if (!IsValid)
            return;

        string year=null,month= null,day= null;
         //身份证号码是否正确
        if(!string.IsNullOrEmpty(txtIdentity.Text))
        {
            
            if(txtIdentity.Text.Length == 18)
            {
                //截取年份
                year = txtIdentity.Text.Substring(6,4);
                //截取月份
                month = txtIdentity.Text.Substring(10,2);
                //截取日
                day = txtIdentity.Text.Substring(12,2);
            }
            else
            {
                //截取年份
                year = "19" + txtIdentity.Text.Substring(6, 2);
                //截取月份
                month = txtIdentity.Text.Substring(8,2);
                //截取日
                day = txtIdentity.Text.Substring(10,2);
            }

            try
            {
                new DateTime(int.Parse(year),int.Parse(month),int.Parse(day));
            }
            catch
            {
                ShowMessage("身份证号码错误");
                return;
            }
        }

        
        System.Text.StringBuilder  logcontent = new System.Text.StringBuilder();
        //是否新增
        bool isAdd = string.IsNullOrEmpty(Request["id"]);

        ////判断员工编号是否重复
        if (isAdd)
        {
            bool exist = manager.ExistCode(MyStateManager.DomainID,  txtCode.Value, false);
            if (exist)
            {
                ShowMessage("员工编号被使用，不能被再次使用");
                return;
            }
        }

     
        if (isAdd)
        {
            _person = new Person();
            _person.DOMAINID = MyStateManager.DomainID;
            _person.Code = txtCode.Value;
        }
        else
        {
            _person = manager.Load(id.Value);
            
            logcontent.Append("<b>修改前条目信息</b><br /> ");
            logcontent.Append(" 姓名:" + _person.Name);
            logcontent.Append(" 编号:" + _person.Code);
            logcontent.Append( " 电话:" +_person.Telephone);
            logcontent.Append( " 传真:" + _person.FAX);
            logcontent.Append( " 电子邮箱:" + _person.EMAIL);
            logcontent.Append(" 身份证号:" + _person.Identity);
            logcontent.Append(" 电子邮箱:" + _person.EMAIL);
            logcontent.Append(" 状态 " + (_person.ACTIVE ? "有效" :"失效"));
            logcontent.Append(" 原更新人:" + _person.LAST_UPDATER);
        }

        
 
        
        
        _person.Name = txtName.Value;
        _person.OrgID = int.Parse(txtHidOrg.Value.Replace('\'',' '));

        
        //更新User 这张表里面的ORG
        if(id != null)
        {
            var userManager = new UserManager();
            var user = userManager.GetUserByPersonID(id.Value);
            if (user != null)
            {
                user.ORGID = _person.OrgID;
                userManager.Save(user);
            }
        }
        _person.Telephone = txtTelephone.Value;
        _person.FAX = txtFax.Value;
        _person.EMAIL = txtMail.Value;
        _person.Sex = ddlSex.Value;
        //ctlTable.SaveValue(_person);
       
        if (ddlPosition.SelectedIndex > 0)
            _person.Position = ddlPosition.SelectedValue;
        _person.Identity = txtIdentity.Text;
        _person.Type = 1;
        _person.ACTIVE = chkValid.Checked ;
        _person.LAST_UPDATER = MyStateManager.Name;
        if (ddlManager.SelectedIndex>0)
        {
            _person.MANAGERID = decimal.Parse(ddlManager.SelectedValue);
        }
        try
        {
            manager.Save(_person);
    
        }
        catch(Exception ex)
        {
           
            ShowMessage("操作失败，错误已经记录日志");
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
                Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, this.MyStateManager.Name,
                this.MyStateManager.UserID, "人员维护 - 异常:" + ex.Message);
            return;
        }

        if (isAdd)
        {
            logcontent.Append("<br /><b>新增条目信息:</b>");
       
        }
        else
        {
            logcontent.Append("<br />修改后条目信息:<br />");
        }

        logcontent.Append(" 姓名:" + _person.Name);
        logcontent.Append( " 电话:" +_person.Telephone);
        logcontent.Append( " 传真:" + _person.FAX);
        logcontent.Append( " 电子邮箱:" + _person.EMAIL);
        logcontent.Append(" 身份证号:" + _person.Identity);
        logcontent.Append(" 状态 " + (_person.ACTIVE ? "有效" : "失效"));

        if (isAdd)
        {
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(Jumpton.SFA.Server.BusinessRule.System.LogType.Info_Change,
                MyStateManager.Name,MyStateManager.UserID.ToString(), "新增人员信息:" + _person.Name, logcontent.ToString());
        }
        else
        {
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(Jumpton.SFA.Server.BusinessRule.System.LogType.Info_Change,
               MyStateManager.Name, MyStateManager.UserID.ToString(), "字人员信息更改:" + _person.Name, logcontent.ToString());
        }

        //跳转到主界面
        Response.Redirect("PeopleList.aspx");

    }


    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        BindManager();
    }
}
